import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  EditReq,
  ScopeContext,
} from '@fast-crud/fast-crud';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';

import { compute, dict } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';
import { lowerFirst } from 'lodash-es';

import {
  DefApplicationApi,
  DefDatasourceConfigApi,
  DefResourceApi,
  findOnlineService,
} from '#/api';
import { DefGenTableApi } from '#/api/devOperation/developer/defGenTable';
import { RouteEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { EntitySuperClassEnum, TemplateEnum, TplEnum } from '#/enums/system';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
  YES_NO_CONSTANT_DICT,
} from '#/plugins/fast-crud/common';
import { downloadByResponse } from '#/utils/file/download';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.developer.defGenTable;

const { createMessage, createConfirm } = useMessage();
const down = (template: TemplateEnum) => {
  let text = '';
  switch (template) {
    case TemplateEnum.WEB_PLUS: {
      text = '下载前端（Vben）';
      break;
    }
    case TemplateEnum.WEB_SOYBEAN: {
      text = '下载前端（Soybean）';
      break;
    }
    case TemplateEnum.WEB_VBEN5: {
      text = '下载前端（Vben5）';
      break;
    }
    default: {
      text = '下载后端';
    }
  }
  return {
    [`download_${template}`]: {
      text,
      size: 'small',
      dropdown: true,
      show: hasPermission(permCode.preview),
      click: async (context: ScopeContext) => {
        const response = await DefGenTableApi.downloadZip(
          [context.row.id],
          template,
        );
        downloadByResponse(response);
        createMessage.success($t('common.tips.downloadSuccess'));
      },
    },
  };
};

const generator = (template: TemplateEnum) => {
  let text = '';
  switch (template) {
    case TemplateEnum.WEB_PLUS: {
      text = '生成前端（Vben）';
      break;
    }
    case TemplateEnum.WEB_SOYBEAN: {
      text = '生成前端（Soybean）';
      break;
    }
    case TemplateEnum.WEB_VBEN5: {
      text = '生成前端（Vben5）';
      break;
    }
    default: {
      text = '生成后端';
    }
  }
  return {
    [`generator_${template}`]: {
      text,
      size: 'small',
      dropdown: true,
      show: hasPermission(permCode.preview),
      click: async (context: ScopeContext) => {
        const defGenVo = { ids: [context.row.id], template };
        await DefGenTableApi.generatorCode(defGenVo);
        if (template === TemplateEnum.BACKEND) {
          createMessage.success(
            `后端代码生成成功，请在${context.row.outputDir}查看`,
          );
        } else {
          createMessage.success(
            `前端代码生成成功，请在${context.row.frontOutputDir}查看`,
          );
        }
      },
    },
  };
};

export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const selectedRowKeys = ref<string[]>([]);
  const { push } = useRouter();

  const editRequest = async (ctx: EditReq) => {
    const { form } = ctx;
    form.tableIdList = props.context.tableIdListRef;
    return await DefGenTableApi.update(form);
  };

  const buildAuthCode = (scope: ScopeContext, type: string) => {
    if (scope.value) {
      createMessage.warning(
        '无法生成！若您仍想采用系统生成的权限编码，请先手动删除已输入的内容',
      );
    } else {
      const model = scope.form;
      const plusApplicationName = model.plusApplicationName;
      const plusModuleName = model.plusModuleName;
      const entityName = lowerFirst(model.entityName);
      if (!plusApplicationName) {
        createMessage.warning('请先填写【前端应用名】');
        return;
      }
      if (!plusModuleName) {
        createMessage.warning('请先填写【前端模块名】');
        return;
      }
      if (!entityName) {
        createMessage.warning('请先填写【实体名称】');
        return;
      }
      const auth = `${plusApplicationName}:${plusModuleName}:${entityName}:${type}`;
      const field = `${type}Auth`;
      scope.form[field] = auth;
    }
  };

  return {
    crudOptions: {
      request: {
        pageRequest: DefGenTableApi.pageRequest,
        editRequest,
        delRequest: DefGenTableApi.delRequest,
        infoRequest: DefGenTableApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: { show: false },
          import: {
            show: hasPermission(permCode.import),
            type: 'primary',
            text: $t('common.title.import'),
            click() {
              props.context.importRef.value.open();
            },
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: DefGenTableApi.removeFn,
            role: permCode.delete,
          }),
          batchEdit: {
            show: hasPermission(permCode.edit),
            text: $t('common.edit'),
            click() {
              if (selectedRowKeys.value?.length > 0) {
                let ids = '';
                const rows = selectedRowKeys.value;
                for (let i = 0; i < rows.length; i++) {
                  const row = rows[i];
                  ids += row;
                  if (i !== rows.length - 1) {
                    ids += ',';
                  }
                }
                push({
                  name: RouteEnum.CODE_GENERATOR_EDIT,
                  params: { id: ids },
                  query: {
                    title: `批量编辑`,
                  },
                });
              } else {
                createMessage.warning('请至少选择一条数据');
              }
            },
          },
          batchPreview: {
            show: hasPermission(permCode.preview),
            text: '预览',
            click() {
              if (selectedRowKeys.value?.length > 0) {
                props.context.previewRef.value.setData({
                  tableIdList: selectedRowKeys.value,
                });
                props.context.previewRef.value.open();
              } else {
                createMessage.warning('请至少选择一条数据');
              }
            },
          },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      form: {
        mode: 'edit',
        // label 宽度
        labelCol: { span: null, style: { width: '150px' } },
        group: {
          type: 'tabs', // collapse, tabs
          // type: 'collapse', // collapse, tabs
          accordion: false, // 手风琴模式
          displayDirective: 'show',
          triggerAreas: ['arrow'],
          groups: {
            base: {
              header: '基础信息',
              columns: [
                'id',
                'name',
                'dsId',
                'author',
                'comment',
                'frontOutputDir',
                'frontSoyOutputDir',
                'frontVben5OutputDir',
                'outputDir',
                'remark',
              ],
            },
            backend: {
              header: '后端信息',
              columns: [
                'entityName',
                'swaggerComment',
                'serviceName',
                'parent',
                'moduleName',
                'childPackageName',
                'entitySuperClass',
                'superClass',
                'isDs',
                'dsValue',
                'isTenantLine',
                'isLombok',
                'isChain',
                'isColumnConstant',
              ],
            },
            front: {
              header: '前端信息',
              columns: [
                'plusApplicationName',
                'plusModuleName',
                'popupType',
                'tplType',
                'treeName',
                'subId',
                'subJavaFieldName',
                'addShow',
                'addAuth',
                'editShow',
                'editAuth',
                'deleteShow',
                'deleteAuth',
                'copyShow',
                'copyAuth',
                'viewShow',
                'viewAuth',
              ],
            },
            sql: {
              header: 'SQL信息',
              columns: [
                'menuApplicationId',
                'menuParentId',
                'menuName',
                'menuIcon',
              ],
            },
          },
        },
      },
      rowHandle: {
        buttons: {
          edit: {
            show: hasPermission(permCode.edit),
            click: (context) => {
              push({
                name: RouteEnum.CODE_GENERATOR_EDIT,
                params: { id: context.row.id },
                query: {
                  title: `表名：${context.row.name}`,
                  content: `实体类：${context.row.entityName}  作者：${context.row.author}`,
                },
              });
            },
          },
          view: { show: false },
          remove: {
            show: hasPermission(permCode.delete),
          },
          copy: { show: false },
          sync: {
            size: 'small',
            type: 'link',
            text: '同步',
            show: hasPermission(permCode.sync),
            click: (context) => {
              createConfirm({
                iconType: 'warning',
                title: `确认同步`,
                content: `确定同步该表新增和删除的字段吗？`,
                onOk: async () => {
                  try {
                    await DefGenTableApi.syncField(context.row.id);
                    createMessage.success('同步成功');
                  } catch {}
                },
              });
            },
          },
          previewFront: {
            text: '预览',
            size: 'small',
            dropdown: true,
            show: hasPermission(permCode.preview),
            click: (context) => {
              props.context.previewRef.value.setData({
                tableIdList: [context.row.id],
              });
              props.context.previewRef.value.open();
            },
          },
          ...down(TemplateEnum.WEB_VBEN5),
          ...down(TemplateEnum.WEB_SOYBEAN),
          ...down(TemplateEnum.WEB_PLUS),
          ...down(TemplateEnum.BACKEND),
          ...generator(TemplateEnum.WEB_VBEN5),
          ...generator(TemplateEnum.WEB_SOYBEAN),
          ...generator(TemplateEnum.WEB_PLUS),
          ...generator(TemplateEnum.BACKEND),
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        id: {
          form: { show: false },
          column: { show: false },
        },
        name: {
          title: $t('devOperation.developer.defGenTable.name'),
          type: 'text',
          search: { component: { disabled: false }, show: true },
          form: {
            component: { disabled: true },
            show: compute(() => {
              return !props.context.batch;
            }),
          },
        },
        dsId: {
          title: $t('devOperation.developer.defGenTable.dsId'),
          addForm: { show: true },
          editForm: { show: true },
          type: 'dict-select',
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await DefDatasourceConfigApi.query({});
            },
          }),
          form: {
            component: { disabled: true },
            show: compute(() => {
              return !props.context.batch;
            }),
          },
          column: { show: false },
        },
        comment: {
          title: $t('devOperation.developer.defGenTable.comment'),
          type: 'text',
          search: { show: true },
          form: {
            helper: {
              position: 'label',
              text: '体现在代码注释中',
            },
            show: compute(() => {
              return !props.context.batch;
            }),
          },
        },
        author: {
          title: $t('devOperation.developer.defGenTable.author'),
          type: 'text',
          search: { show: true },
          form: {
            helper: {
              position: 'label',
              text: '体现在代码注释中的 @author',
            },
          },
        },
        outputDir: {
          title: $t('devOperation.developer.defGenTable.outputDir'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              text: '在dev环境生成后端项目的完整路径，非dev环境不使用该参数',
            },
          },
        },
        frontOutputDir: {
          title: $t('devOperation.developer.defGenTable.frontOutputDir'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              text: '在dev环境生成后端项目的完整路径，非dev环境不使用该参数',
            },
          },
        },
        frontSoyOutputDir: {
          title: $t('devOperation.developer.defGenTable.frontSoyOutputDir'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              text: '在dev环境生成后端项目的完整路径，非dev环境不使用该参数',
            },
          },
        },
        frontVben5OutputDir: {
          title: $t('devOperation.developer.defGenTable.frontVben5OutputDir'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              text: '在dev环境生成后端项目的完整路径，非dev环境不使用该参数',
            },
          },
        },
        remark: {
          title: $t('devOperation.developer.defGenTable.remark'),
          type: 'textarea',
          column: { show: false },
        },

        entityName: {
          title: $t('devOperation.developer.defGenTable.entityName'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute(() => {
              return !props.context.batch;
            }),
            helper: {
              position: 'label',
              text: '修改实体名称后，会影响Controller、Service、Manager、Mapper、VO的名称',
            },
          },
        },
        swaggerComment: {
          title: $t('devOperation.developer.defGenTable.swaggerComment'),
          type: 'text',
          search: { show: false },
          column: { show: false },
          form: {
            show: compute(() => {
              return !props.context.batch;
            }),
            helper: {
              position: 'label',
              text: '体现在swagger文档',
            },
          },
        },
        serviceName: {
          title: $t('devOperation.developer.defGenTable.serviceName'),
          type: 'dict-select',
          dict: dict({
            label: 'value',
            async getData() {
              return await findOnlineService();
            },
          }),
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '1. 确保前端ServicePrefixEnum中的枚举值KEY 与 后端”服务名“和lamp-gateway-server.yml中“uri”保持一致\n2. 确保前端ServicePrefixEnum中的枚举值VALUE 与 后端lamp-gateway-server.yml中“predicates”配置一致\n如： lamp-base、lamp-base-api、lamp-base-biz、lamp-base-controller、lamp-base-server 中的 base\n如： lamp-system-server 中的 system',
            },
          },
        },
        parent: {
          title: $t('devOperation.developer.defGenTable.parent'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '生成业务代码的基础包包名\n如："top.tangyh.lamp.base.dao.common" 中的 "top.tangyh.lamp"',
            },
          },
        },
        moduleName: {
          title: $t('devOperation.developer.defGenTable.moduleName'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '建议跟{服务名一致}保持一致\n如："top.tangyh.lamp.base.dao.common" 中的 "base" \n如："top.tangyh.lamp.file.dao" 中的 "file"',
            },
          },
        },
        childPackageName: {
          title: $t('devOperation.developer.defGenTable.childPackageName'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '如："top.tangyh.lamp.base.dao.common" 中的 "common"  \n 如："top.tangyh.lamp.base.dao.system" 中的 "system" ',
            },
          },
        },
        entitySuperClass: {
          title: $t('devOperation.developer.defGenTable.entitySuperClass'),
          type: 'dict-select',
          dict: backendDict({ type: 'EntitySuperClassEnum', isEnum: true }),
          column: { show: false },
          form: {
            valueChange({ form, value }) {
              form.tplType =
                value === EntitySuperClassEnum.TREE_ENTITY
                  ? TplEnum.TREE
                  : TplEnum.SIMPLE;
              createMessage.success(`已级联修改使用的模板为${form.tplType}`);
            },
            helper: {
              position: 'label',
              text: '实体类的父类',
            },
          },
        },
        superClass: {
          title: $t('devOperation.developer.defGenTable.superClass'),
          type: 'dict-select',
          dict: backendDict({ type: 'SuperClassEnum', isEnum: true }),
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: 'Controller、Service、Manager、Mapper类的父类',
            },
          },
        },
        isDs: {
          title: $t('devOperation.developer.defGenTable.isDs'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.isDs ? 12 : 24;
              }),
            },
            helper: {
              text: 'datasource模式才会使用该参数，column、none模式请忽略',
            },
          },
        },
        dsValue: {
          title: $t('devOperation.developer.defGenTable.dsValue'),
          type: 'text',
          column: { show: false },
          form: {
            rule: {
              required: compute((context: ComputeContext) => {
                return Boolean(context.form.isDs);
              }),
              message: '请填写数据源',
            },
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.isDs);
            }),
            helper: {
              text: 'datasource模式才会使用该参数，column、none模式请忽略',
            },
          },
        },
        isTenantLine: {
          title: $t('devOperation.developer.defGenTable.isTenantLine'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            helper: {
              text: 'column模式才会使用该参数，datasource、none模式请忽略',
            },
          },
        },
        isLombok: {
          title: $t('devOperation.developer.defGenTable.isLombok'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
        },
        isChain: {
          title: $t('devOperation.developer.defGenTable.isChain'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
        },
        isColumnConstant: {
          title: $t('devOperation.developer.defGenTable.isColumnConstant'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
        },

        plusApplicationName: {
          title: $t('devOperation.developer.defGenTable.plusApplicationName'),
          type: 'text',
          column: { show: false },
          form: {
            component: {
              name: 'a-auto-complete',
              options: [{ value: 'devOperation' }, { value: 'basic' }],
            },
            helper: {
              position: 'label',
              text: '1. src/views/ 目录下的 basic 或 devOperation 或 其他 \n 2. src/api/ 或 src/service/fetch/ 目录下的 basic 或 devOperation 或 其他 \n 3. src/locales/lang/{语言}/ 目录下的 basic 或 devOperation 或 其他 \n 4. 想要修改下拉框中的选项，请在前端页面中修改',
            },
          },
        },
        plusModuleName: {
          title: $t('devOperation.developer.defGenTable.plusModuleName'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '1. src/api/{前端应用名} 目录下的文件夹名 \n 2. src/views/{前端应用名} 目录下的文件夹名 \n 3. src/locales/lang/{语言}/{前端应用名} 目录下的文件夹名 \n 如：src/views/devOperation/ 下的 application、developer 等目录',
            },
          },
        },
        popupType: {
          title: $t('devOperation.developer.defGenTable.popupType'),
          type: 'dict-radio',
          dict: backendDict({ type: 'PopupTypeEnum', isEnum: true }),
          column: { show: false },
          form: {
            helper: {
              position: 'label',
              text: '前端代码index.vue页面点击新增或编辑时，弹窗的打开方式',
            },
          },
        },
        tplType: {
          title: $t('devOperation.developer.defGenTable.tplType'),
          type: 'dict-radio',
          dict: backendDict({ type: 'TplEnum', isEnum: true }),
          column: { show: false },
          form: {
            valueChange({ form, value }) {
              form.entitySuperClass =
                value === TplEnum.TREE
                  ? EntitySuperClassEnum.TREE_ENTITY
                  : EntitySuperClassEnum.ENTITY;
              createMessage.success(
                `已级联修改父类实体为${form.entitySuperClass}`,
              );
            },
            helper: {
              position: 'label',
              text: '前端代码生成何种操作风格的页面',
            },
          },
        },
        addAuth: {
          title: $t('devOperation.developer.defGenTable.addAuth'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.addShow);
            }),
            suffixRender(scope: ScopeContext) {
              return (
                <Button
                  ghost
                  onClick={() => buildAuthCode(scope, 'add')}
                  type="primary"
                >
                  生成
                </Button>
              );
            },
            helper: {
              text: '系统规则：{前端应用名}:{前端模块名}:{实体名称}:add',
            },
          },
        },
        editAuth: {
          title: $t('devOperation.developer.defGenTable.editAuth'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.editShow);
            }),
            suffixRender(scope: ScopeContext) {
              return (
                <Button
                  ghost
                  onClick={() => buildAuthCode(scope, 'edit')}
                  type="primary"
                >
                  生成
                </Button>
              );
            },
            helper: {
              text: '系统规则：{前端应用名}:{前端模块名}:{实体名称}:edit',
            },
          },
        },
        deleteAuth: {
          title: $t('devOperation.developer.defGenTable.deleteAuth'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.deleteShow);
            }),
            suffixRender(scope: ScopeContext) {
              return (
                <Button
                  ghost
                  onClick={() => buildAuthCode(scope, 'delete')}
                  type="primary"
                >
                  生成
                </Button>
              );
            },
            helper: {
              text: '系统规则：{前端应用名}:{前端模块名}:{实体名称}:delete',
            },
          },
        },
        viewAuth: {
          title: $t('devOperation.developer.defGenTable.viewAuth'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.viewShow);
            }),
            suffixRender(scope: ScopeContext) {
              return (
                <Button
                  ghost
                  onClick={() => buildAuthCode(scope, 'view')}
                  type="primary"
                >
                  生成
                </Button>
              );
            },
            helper: {
              text: '系统规则：{前端应用名}:{前端模块名}:{实体名称}:view',
            },
          },
        },
        copyAuth: {
          title: $t('devOperation.developer.defGenTable.copyAuth'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return Boolean(context.form.copyShow);
            }),
            suffixRender(scope: ScopeContext) {
              return (
                <Button
                  ghost
                  onClick={() => buildAuthCode(scope, 'copy')}
                  type="primary"
                >
                  生成
                </Button>
              );
            },
            helper: {
              text: '系统规则：{前端应用名}:{前端模块名}:{实体名称}:copy',
            },
          },
        },
        addShow: {
          title: $t('devOperation.developer.defGenTable.addShow'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.addShow ? 12 : 24;
              }),
            },
          },
        },
        editShow: {
          title: $t('devOperation.developer.defGenTable.editShow'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.editShow ? 12 : 24;
              }),
            },
          },
        },
        deleteShow: {
          title: $t('devOperation.developer.defGenTable.deleteShow'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.deleteShow ? 12 : 24;
              }),
            },
          },
        },
        copyShow: {
          title: $t('devOperation.developer.defGenTable.copyShow'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.copyShow ? 12 : 24;
              }),
            },
          },
        },
        viewShow: {
          title: $t('devOperation.developer.defGenTable.viewShow'),
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          column: { show: false },
          form: {
            col: {
              span: compute((context: ComputeContext) => {
                return context.form.viewShow ? 12 : 24;
              }),
            },
          },
        },
        menuApplicationId: {
          title: $t('devOperation.developer.defGenTable.menuApplicationId'),
          type: 'dict-select',
          column: { show: false },
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await DefApplicationApi.query({});
            },
            immediate: false,
            // async onReady(context) {
            //   const fcRef = context.getComponentRef('menuParentId', false);
            //   fcRef?.reloadDict();
            // }
          }),
          form: {
            helper: {
              text: '当前功能生成后，菜单属于哪个应用？',
            },
            valueChange({ form, value, getComponentRef }) {
              form.menuParentId = undefined;
              if (value) {
                getComponentRef('menuParentId').reloadDict();
              }
            },
          },
        },
        menuParentId: {
          title: $t('devOperation.developer.defGenTable.menuParentId'),
          type: 'dict-tree',
          column: { show: false },
          dict: dict({
            isTree: true,
            prototype: true,
            value: 'id',
            label: 'name',
            async getData(context) {
              return context.form?.menuApplicationId
                ? await DefResourceApi.tree({
                    applicationId: context.form?.menuApplicationId,
                  })
                : [];
            },
          }),
          form: {
            helper: {
              text: '当前功能生成后，显示在左侧菜单的位置',
            },
          },
        },
        menuName: {
          title: $t('devOperation.developer.defGenTable.menuName'),
          type: 'text',
          column: { show: false },
          form: {
            helper: {
              text: '当前功能生成后，显示在左侧的菜单名',
            },
          },
        },
        menuIcon: {
          title: $t('devOperation.developer.defGenTable.menuIcon'),
          type: 'text',
          column: { show: false },
        },
        treeName: {
          title: $t('devOperation.developer.defGenTable.treeName'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return context.form.tplType === TplEnum.TREE;
            }),
            col: { span: 24 },
            rule: {
              required: compute((context: ComputeContext) => {
                return context.form.tplType === TplEnum.TREE;
              }),
              message: '请填写树结构名称字段名',
            },
            helper: {
              text: '树型页面，显示在树节点上的字段',
            },
          },
        },
        subId: {
          title: $t('devOperation.developer.defGenTable.subId'),
          // type: 'text',
          type: 'dict-select',
          dict: dict({
            getData: async () => {
              const tableList = await DefGenTableApi.query({});
              return tableList.map((item) => {
                return {
                  value: item.id,
                  label: item.name,
                };
              });
            },
          }),
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return context.form.tplType === TplEnum.MAIN_SUB;
            }),
            rule: {
              required: compute((context: ComputeContext) => {
                return context.form.tplType === TplEnum.MAIN_SUB;
              }),
              message: '请选择从表',
            },
            helper: {
              text: '主从页面，从表需要先导入并配置相关信息',
            },
          },
        },
        subJavaFieldName: {
          title: $t('devOperation.developer.defGenTable.subJavaFieldName'),
          type: 'text',
          column: { show: false },
          form: {
            show: compute((context: ComputeContext) => {
              return context.form.tplType === TplEnum.MAIN_SUB;
            }),
            rule: {
              required: compute((context: ComputeContext) => {
                return context.form.tplType === TplEnum.MAIN_SUB;
              }),
              message: '从表实体字段名',
            },
            helper: {
              text: '主从页面，从表的外键Java实体类的字段名',
            },
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = {
  addForm: {
    rules: {},
  },
  editForm: {
    rules: {},
  },
};
